package com.chatplus.application.listener.order;

import com.chatplus.application.common.constant.RedisPrefix;
import com.chatplus.application.domain.entity.orders.OrderEntity;
import com.chatplus.application.enumeration.OrderStatusEnum;
import com.chatplus.application.event.GenericEvent;
import com.chatplus.application.event.order.OrderUpdateEvent;
import com.chatplus.application.event.order.dto.OrderRequestEvent;
import com.chatplus.application.service.account.UserProductLogService;
import com.chatplus.application.service.orders.OrderService;
import org.redisson.api.RedissonClient;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * 订单事件监听
 *
 * @author chj
 * @date 2024/2/6
 **/
@Component
public class OrderEventListener {
    private final OrderService orderService;
    private final RedissonClient redissonClient;
    private final UserProductLogService userProductLogService;

    public OrderEventListener(OrderService orderService, RedissonClient redissonClient, UserProductLogService userProductLogService) {
        this.orderService = orderService;
        this.redissonClient = redissonClient;
        this.userProductLogService = userProductLogService;
    }
    @EventListener(classes = OrderUpdateEvent.class)
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void paySuccessEventListener(GenericEvent<OrderRequestEvent> event) {
        OrderRequestEvent orderRequestEvent = event.getData();
        if (orderRequestEvent == null) {
            return;
        }
        OrderStatusEnum status = orderRequestEvent.getStatus();
        Long orderId = orderRequestEvent.getOrderId();
        OrderEntity orderEntity = orderService.getById(orderId);
        orderEntity.setStatus(status);
        orderEntity.setTradeNo(orderRequestEvent.getTradeTransactionId());
        orderEntity.setPayTime(orderRequestEvent.getSuccessAt());
        orderService.updateById(orderEntity);
        // 给用户新增对应的套餐
        if (status == OrderStatusEnum.SUCCESS) {
            userProductLogService.addProductToUser(orderEntity.getUserId(), orderEntity.getProductId(), orderEntity.getId());
        }
        // 事务提交后清空缓存
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                // 清空缓存
                redissonClient.getBucket(RedisPrefix.PAY_STATUS_PREFIX + orderEntity.getId()).deleteAsync();
            }
        });
    }
}
